/**
 * Created by YJH on 2018/6/4.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    DeviceEventEmitter,
} from 'react-native';
import ParallaxScrollView from 'react-native-parallax-scroll-view';
import NavigationBarUtil from '../../util/NavigationBarUtil';
import FavoriteDao from '../../expand/dao/FavoriteDao';
import {FLAG_STORAGE} from '../../expand/dao/DataRespository';
import FavoriteUtil from '../../util/FavoriteUtil';
import RespositoryCell from '../../common/RespositoryCell';
import RepositoryAboutUtil from '../../expand/dao/RepositoryAboutUtil';
import ThemeDao from '../../expand/dao/ThemeDao';

export var FLAG_ABOUT_COMMON = {flag_about: 'about', flag_about_me: 'about_me'};
export default class AboutCommon {

    /**
     * 功能；
     * @param props
     * @param updateState 方法
     * @param flag_about
     */
    constructor(props, updateState, flag_about, config) {
        this.props = props;
        this.updateState = updateState;
        this.flag = flag_about;
        this.repositories = [];
        this.favoriteKeys = null;
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular);
        this.config=config;
        this.repositoryAboutUtil=new RepositoryAboutUtil(this);
    }
    componentWillMount(){
        this.theme=ThemeDao.getTime().themeColor;
    }
    componentDidMount(){
        if(this.flag===FLAG_ABOUT_COMMON.flag_about){
            this.repositoryAboutUtil._fetchRepository(this.config.info.currentRepoUrl);
        }else{
            var urls=[];
            var items=this.config.items;
            items.forEach(item=>{
                urls.push(this.config.info.url+item);
            });
            this.repositoryAboutUtil.fetchRepositorys(urls);
        }
    }

    /**
     * 功能：接收通知去更新数据
     * @param items
     */
    onNotifyDataChanged(items) {
        this.updateRepository(items);
    }


    /**
     * 功能：更新用户已收藏的状态
     * 使用同步方式
     * @param repositories
     */
    async updateRepository(repositories) {
        if (!repositories)return;
        this.repositories = repositories;
        if (!this.favoriteKeys) {
            this.favoriteKeys = await this.favoriteDao.getFavoriteKeys();
        }

        let projectModules = [];
        let items = this.repositories;
        for (let i = 0, l = items.length; i < l; i++) {
            let data = items[i];
            projectModules.push({
                isFavorite: FavoriteUtil.checkFavorite(items[i], this.favoriteKeys ? this.favoriteKeys : []),
                item: data.item?data.item:data,
            })
        }

        this.updateState({
            projectModules:projectModules,
        })
    }
    onFavoritePressed(item, isFavorite) {
        if (isFavorite)
            this.favoriteDao.savaFavoriteItem(item.id.toString(), JSON.stringify(item));
        else this.favoriteDao.removeFavoriteItem(item.id.toString())
    }

    /**
     * 功能：创建项目视图
     * @param projectModules
     * @returns {*}
     */
    renderRepository(projectModules){
        if(!projectModules || projectModules.length===0)return null;
        let views=[];

        projectModules.map(projectModule=>{
            views.push(
                <RespositoryCell
                    key={projectModule.item.id}
                    projectModule={projectModule}
                    onFavoritePressed={(item, isFavorite) => this.onFavoritePressed(item, isFavorite)}

                    {...this.props}
                />
            )
        });

        return views;
    }

    getParallaxScrollConfig(params) {
        //这里抽取参数属性的方式很独特
        let config = {};
        config.renderBackground = () => (
            <View key="background">
                <Image source={{
                    uri: params.renderBackground,
                    width: window.width,
                    height: PARALLAX_HEADER_HEIGHT
                }}/>
                <View style={{
                    position: 'absolute',
                    top: 0,
                    width: window.width,
                    backgroundColor: 'rgba(0,0,0,.4)',
                    // backgroundColor: '#2196F3',
                    height: PARALLAX_HEADER_HEIGHT
                }}/>
            </View>
        );

        config.renderForeground = () => (
            <View key="parallax-header" style={ styles.parallaxHeader }>
                <Image style={ styles.avatar } source={{
                    uri: params.renderForeground,
                    width: AVATAR_SIZE,
                    height: AVATAR_SIZE
                }}/>
                <Text style={ styles.sectionSpeakerText }>
                    {params.userName}
                </Text>
                <Text style={ styles.sectionTitleText }>
                    {params.userProfile}
                </Text>
            </View>
        );

        config.renderStickyHeader = () => (
            <View key="sticky-header" style={styles.stickySection}>
                <Text style={styles.fixedSectionText}
                >
                    {params.userName}
                </Text>
            </View>
        );

        config.renderFixedHeader = () => (
            <View key="fixed-header" style={styles.fixedSection}>
                {NavigationBarUtil.getLeftButton(() => this.props.navigator.pop())}
            </View>
        );

        return config;
    }

    /**
     * @param params 个人信息{}
     * @param contentView item-view
     * @returns {XML}
     */
    render(params, favoriteView, contentView) {
        return (
            <ParallaxScrollView
                headerBackgroundColor={this.props.theme.themeColor}
                backgroundColor={this.props.theme.themeColor}
                stickyHeaderHeight={ STICKY_HEADER_HEIGHT }
                parallaxHeaderHeight={ PARALLAX_HEADER_HEIGHT }
                backgroundSpeed={10}
                {...this.getParallaxScrollConfig(params)}
            >
                {favoriteView}
                {contentView}
            </ParallaxScrollView>
        );
    }
}

const window = Dimensions.get('window');

const AVATAR_SIZE = 120;
const ROW_HEIGHT = 60;
const PARALLAX_HEADER_HEIGHT = 350;
const STICKY_HEADER_HEIGHT = 50;//70

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: this.theme
    },
    background: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: window.width,
        height: PARALLAX_HEADER_HEIGHT
    },
    stickySection: {
        height: STICKY_HEADER_HEIGHT,
        width: window.width,//300
        justifyContent: 'center',
        alignItems: 'center'
    },
    stickySectionText: {
        color: 'white',
        fontSize: 20,
        margin: 10,

    },
    fixedSection: {
        position: 'absolute',
        alignItems: 'center',
        bottom: 0,
        top: 5,
        right: window.width - 40,
    },
    fixedSectionText: {
        color: 'white',
        fontSize: 20,

    },
    parallaxHeader: {
        alignItems: 'center',
        flex: 1,
        flexDirection: 'column',
        paddingTop: 100
    },
    avatar: {
        marginBottom: 10,
        borderRadius: AVATAR_SIZE / 2
    },
    sectionSpeakerText: {
        color: 'white',
        fontSize: 24,
        paddingVertical: 5
    },
    sectionTitleText: {
        color: 'white',
        fontSize: 18,
        paddingVertical: 5
    },
    row: {
        overflow: 'hidden',
        paddingHorizontal: 10,
        height: ROW_HEIGHT,
        backgroundColor: 'white',
        borderColor: this.theme,
        borderBottomWidth: 1,
        justifyContent: 'center'
    },
    rowText: {
        fontSize: 20
    },

});